<!--  -->
<template>
    <div class='page-main'>
        <CustomForm :formInline="formInline" @onSubmit="onSubmit" @resetTable="resetTable">
            <el-form-item label="总运单ID">
                <el-input v-model="formInline.add_id" placeholder="请输入运单ID"></el-input>
            </el-form-item>
            <el-form-item label="分运单ID">
                <el-input v-model="formInline.id" placeholder="请输入运单ID"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="formInline.type" placeholder="请选择" @change="selectTypeHandle">
                    <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="司机姓名">
                <el-input v-model="formInline.name" placeholder="请输入司机姓名"></el-input>
            </el-form-item>

            <el-form-item label="公司名称">
                <!-- <el-input v-model="formInline.company_name" placeholder="请输入公司名称"></el-input> -->
                <el-select v-model="formInline.company_name" placeholder="选择公司名称" clearable @change="selectCompanyName">
                    <el-option v-for="(item, index) in ahCompanyList" :label="item" :value="item"
                        :key="index"></el-option>
                </el-select>
            </el-form-item>


            <el-form-item label="手机号">
                <el-input v-model="formInline.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>

            <el-form-item label="接单时间">
                <el-date-picker v-model="pickerDateArr" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="changeDatePicker"></el-date-picker>
            </el-form-item>

            <el-form-item label="发货地">
                <el-cascader v-model="searchAddressStart" :props="{ checkStrictly: true }" clearable
                    :options="regionData" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="收货地">
                <el-cascader v-model="searchAddressEnd" :props="{ checkStrictly: true }" clearable :options="regionData"
                    style="width: 100%;" />
            </el-form-item>
            <el-form-item label="搜索公司">
                <el-input v-model="formInline.company_search" placeholder="请输入公司名称"></el-input>
            </el-form-item>
            <el-form-item label="车牌号">
                <el-input v-model="formInline.car_name" placeholder="请输入车牌号"></el-input>
            </el-form-item>
            <el-form-item label="卸货时间">
                <el-date-picker v-model="pickerDateArrEnd" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="changeDatePicker"></el-date-picker>
            </el-form-item>

            <el-form-item label="所属地区">
                <el-select v-model="formInline.area_status" placeholder="选择所属公司" @change="selectArea">
                    <el-option label="全部" :value="-1"></el-option>
                    <el-option v-for="(item, index) in getOfficesList" :key="item" :label="item"
                        :value="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="异常状态">
                <el-select v-model="formInline.error_status" placeholder="选择异常状态" @change="selectArea">
                    <el-option label="全部" :value="-1"></el-option>
                    <el-option label="提货异常" :value="1"></el-option>
                    <el-option label="卸货异常" :value="2"></el-option>
                    <el-option label="运输异常" :value="3"></el-option>
                    <el-option label="结算异常" :value="4"></el-option>
                    <!-- <el-option v-for="(item, index) in getOfficesList" :key="item" :label="item"
                        :value="index"></el-option> -->
                </el-select>
            </el-form-item>
            <!-- <template slot="btnBoxHeader">
                <el-button type="success" @click="batchWaybillStatus">批量修改运单状态</el-button>
            </template> -->
        </CustomForm>
        <CustomDescriptions :data="descriptionsData" :styleBox="{}"></CustomDescriptions>


        <el-table :data="list" style="width: 100%" height="540" v-loading="tableLoading"
            @selection-change="handleSelectionChange">
            <el-table-column align="center" width="80">
                <template slot-scope="scope">
                    <!-- <svg v-if="false"
                        style="width: 3em;height:1rem;vertical-align: -0.15em;fill: currentColor;overflow: hidden;"
                        aria-hidden="true">
                        <use xlink:href="#icon-prePayIcon" />
                    </svg > -->
                    <!-- 异常状态 -->
                    <StatusTag v-if="scope.row.is_transfer_order == 1" :statusTitle="'转单'" :isError="false" :status="2"  />
                </template>
            </el-table-column>
            <el-table-column align="center" width="80" v-if="false">
                <template slot-scope="scope">
                    <!-- <svg v-if="false"
                        style="width: 3em;height:1rem;vertical-align: -0.15em;fill: currentColor;overflow: hidden;"
                        aria-hidden="true">
                        <use xlink:href="#icon-prePayIcon" />
                    </svg > -->
                    <StatusTag :status="scope.row.advance_payment_status" :yund_id="scope.row.id" />
                </template>
            </el-table-column>
            
            <!-- <el-table-column type="selection" width="25" :selectable="selectableStatus">
            </el-table-column> -->
            <el-table-column prop="area_company" label="所属地区" width="100" align="center">
            </el-table-column>
            <el-table-column prop="id" label="运单ID" width="100" align="center">
                <template slot-scope="scope">
                    <span @click="openViewWaybillInfo(scope.row.add_id)" style="cursor: pointer;">{{ scope.row.add_id +
                        '-' + scope.row.id
                        }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="sj_name" label="司机姓名" width="80" align="center">
                <template slot-scope="scope">
                        {{ $maskString(scope.row.sj_name) }}
                </template>
            </el-table-column>
            <!-- <el-table-column prop="mobile" label="手机号" align="center">
            </el-table-column> -->
            <el-table-column prop="cph" label="车牌号" width="100" align="center">
            </el-table-column>
            <el-table-column prop="company_name" label="公司名称" align="center" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="ship_address" label="发货地" :show-overflow-tooltip="true" align="center">
            </el-table-column>
            <el-table-column prop="to_address" label="收货地" :show-overflow-tooltip="true" align="center">
            </el-table-column>
            <el-table-column prop="add_time" label="接单时间" :show-overflow-tooltip="true" align="center">
            </el-table-column>
            <el-table-column prop="th_time" label="提货时间" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.status == '0'">---</span>
                    <span v-else>{{ scope.row.th_time }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="dd_time" label="卸货时间" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <span v-if="[4, 5, 6, 7].includes(scope.row.status)">{{ scope.row.dd_time }}</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <el-table-column prop="check_time" label="审核时间" :show-overflow-tooltip="true" align="center">
            </el-table-column>
            <!-- <el-table-column prop="unit_price" label="运费单价" width="80" align="center">
            </el-table-column> -->
            <el-table-column prop="kg" label="发货重量" align="center" width="80">
                <template slot-scope="scope">
                    <span :style="{ color: (scope.row.kg ? '' : 'red') }">{{ scope.row.kg }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="unloading_weight" label="卸货重量" align="center" width="80">
                <template slot-scope="scope">
                    <span :style="{ color: (scope.row.unloading_weight ? '' : 'red') }">{{ scope.row.unloading_weight
                        }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="运费" align="center" width="80">
            </el-table-column>
            <el-table-column prop="status" label="运输状态" width="80" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.status == '0'">待提货</span>
                    <span v-else-if="scope.row.status == '1'">拒绝</span>
                    <span v-else-if="scope.row.status == '2'">确认</span>
                    <span v-else-if="scope.row.status == '3'" style="color:blue">运输中</span>
                    <span v-else-if="scope.row.status == '4'" style="color:green">完成</span>
                    <span v-else-if="scope.row.status == '5'" style="color:#ff9900">待结算</span>
                    <span v-else-if="scope.row.status == '6'" style="color:green">结算</span>
                    <span v-else-if="scope.row.status == '7'">结算失败</span>
                </template>
            </el-table-column>
            <el-table-column prop="error_status" label="异常状态" width="80" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.error_status == 1" style="color:red">提货异常</span>
                    <span v-if="scope.row.error_status == 2" style="color:red">卸货异常</span>
                    <span v-if="scope.row.error_status == 3" style="color:red">运输异常</span>
                    <span v-if="scope.row.error_status == 4" style="color:red">结算异常</span>
    
                </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="240" align="center">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="checkBill(scope.row)">查看</el-button>
                    <el-button type="danger" size="mini" @click="deleteBill(scope.row.id)" :disabled="scope.row.is_transfer_order == 1 || disabledDelBtn(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page.sync="formInline.page" :page-sizes="[10, 20, 30, 50]" :page-size="formInline.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <el-dialog title="查看异常运单" top="15vh" :visible.sync="dialogVisible" width="70%">
            <CheckErrorBill v-if="dialogVisible" :billData="billData"  @refreshTable="refreshTable" />
        </el-dialog>


    </div>
</template>

<script>
import { regionData } from "element-china-area-data";
import { getCodeToText  } from '@/utils/tool';
import { getOfficesList } from '@/utils/auth';
import { getSubBillListError,getContractLink,deleteErrorBill,getSubBillList, waybillDetails, viewReceipts, updateViewReceipts, getAhCompanyList, updateBillStatus, deleteSubBill } from '@/api/businessUser/waybill';
import CheckErrorBill from "./components/checkErrorBill.vue";
export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
        CheckErrorBill,
    },
    data() {
        //这里存放数据
        return {
            dialogVisible:false,
            regionData,
            traceId:'',
            traceRow:'',
            getOfficesList: getOfficesList(),
            formInline: {
                id: "",//id搜索
                add_id: '',//分运单id
                type: -1,
                time: '',
                endTime: "",
                name: "",
                car_name: "",
                phone: "",
                page: 1,
                pageSize: 10,
                company_search: "",
                company_name: "",
                start_province: "",
                start_city: "",
                end_province: "",
                end_city: "",
                sfd: "",
                zd: "",
                reach_time: "",//卸货时间
                area_status: 0,
                error_status:-1,
            },
            billData:{},//当前选中行查看的异常数据信息
            options: [
                {
                    name: '全部',
                    value: -1
                },
                {
                    name: '待提货',
                    value:0
                },
                {
                    name: '运输中',
                    value: 3
                },
                {
                    name: '已完成',
                    value: 4
                },
                {
                    name: '待结算',
                    value: 5
                },
                {
                    name: '已结算',
                    value: 6
                },
            ],
            list: [],//分运单列表
            pickerDateArr: "",
            pickerDateArrEnd: "",
            tableLoading: false,
            total: 0,
            checkTrace: false,

            dialogReceipts: false,//回单dialog显示

            viewReceiptsImgs: {//回单的三张图片
                pic: "",
                shd: "",
                xh_img: "",
                id: ""
            },
            checkWaybillDialog: false,//核对运单
            billDetail: {},//核对运单数据

            descriptionsData: [
                {
                    label: "总单数",
                    count: 0,
                    unit: "(单)"
                },
                {
                    label: "总吨数",
                    count: 0,
                    unit: "(吨)"
                },
                {
                    label: "总金额",
                    count: 0,
                    unit: "(元)"
                },
            ],

            ahCompanyList: [],//总公司公司列表

            searchAddressStart: '',//始发地选择
            searchAddressEnd: '',//终点选择

            multipleSelection: [],

            driverPositionDialog: false,

            yun_id: '',

            // dialogVisible: false,//查看运单的dialog

            waybillDetail: {
                id: '',
            }
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {
        pickerDateArr: {
            handler(newV, oldV) {
                if (newV) {
                    this.formInline.time = newV[0]
                    this.formInline.endTime = newV[1]
                } else {
                    this.formInline.time = ''
                    this.formInline.endTime = ''
                }
            }
        },
        pickerDateArrEnd: {//卸货时间
            handler(newV, oldV) {
                if (newV) {
                    this.formInline.reach_time = newV.join(' - ');
                } else {
                    this.formInline.reach_time = '';
                }
            }
        },
        searchAddressStart: {
            handler(newV, oldV) {
                let res = getCodeToText(newV);
                this.formInline.start_province = '';
                this.formInline.start_city = '';
                this.formInline.sfd = '';

                if (newV.length >= 1) {
                    this.formInline.start_province = res[0];
                }
                if (newV.length >= 2) {
                    if (res[0].includes('市')) {
                        this.formInline.start_city = res[0];
                    } else {
                        this.formInline.start_city = res[1].substring(0, res[1].length - 1);
                    }
                }
                if (newV.length == 3) {
                    this.formInline.sfd = newV[2]
                }
            }
        },
        searchAddressEnd: {
            handler(newV, oldV) {
                let res = getCodeToText(newV);
                this.formInline.end_province = '';
                this.formInline.end_city = '';
                this.formInline.zd = '';

                if (newV.length >= 1) {
                    this.formInline.end_province = res[0];
                }
                if (newV.length >= 2) {
                    if (res[0].includes('市')) {
                        this.formInline.end_city = res[0];
                    } else {
                        this.formInline.end_city = res[1].substring(0, res[1].length - 1);
                    }
                }
                if (newV.length == 3) {
                    this.formInline.zd = newV[2]
                }
            }
        },
        'formInline.company_search': {
            handler(newV, oldV) {
                if (newV) {
                    this.formInline.company_name = "";
                }
            }
        }
    },
    //方法集合
    methods: {
        disabledDelBtn(row){
            //待结算，结算状态可以删除
            console.log('row.status',row.status);            
            if([6].includes(row.status)){
                return true
            }else{
                //待结算+结算异常不可以删除
                if([5].includes(row.status) && row.error_status == 4){
                    return true
                }
                return false
            }
        },
        refreshTable() {
            this.checkWaybillDialog = false;
            this.dialogVisible = false;
            this.getSubBillList();
        },
        async contractHandler(data) {
            let res = await getContractLink(data);
            if (res.code == 200) {
                window.open(res.url, "_blank");
            }
        },
        async getSubBillList() {
            this.tableLoading = true;
            let res = await getSubBillListError(this.formInline);
            if (res.code == 200) {
                this.list = res.data;
                this.total = res.extra.total;
                this.descriptionsData[0].count = this.total;
                this.descriptionsData[1].count = res.extra.weight;
                this.descriptionsData[2].count = res.extra.total_price;
            }
            this.tableLoading = false;
        },
        openTrace(row){
            this.traceRow = row; 
            this.traceId = row.id;
            this.checkTrace = true
        },
        onSubmit() {
            this.formInline.page = 1;
            this.getSubBillList();
        },
        resetTable() {
            this.formInline = {
                id: "",
                add_id: "",
                type: -1,
                time: '',
                endTime: "",
                name: "",
                car_name: "",
                phone: "",
                page: 1,
                pageSize: 10,
                company_search: "",
                company_name: "",
                start_province: "",
                start_city: "",
                end_province: "",
                end_city: "",
                sfd: "",
                zd: "",
                reach_time: "",//卸货时间
                area_status: 0,
                error_status:-1,
            };
            this.pickerDateArr = "";
            this.searchAddressStart = [];
            this.searchAddressEnd = [];
            this.pickerDateArr = [];
            this.pickerDateArrEnd = [];
            this.getSubBillList();
        },
        checkBill(row){
            this.billData = row;
            this.dialogVisible = true;
        },
        deleteBill(id){
            this.$confirm('确定删除该异常运单吗?', '提示', {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                let res = await deleteErrorBill({
                    id
                })
                if (res.code == 200) {
                    this.$message.success(res.msg)
                    this.refreshTable();
                } 
            }).catch(() => {

            })
        },
        changeDatePicker() {//日期选择完的回调
            this.$nextTick(() => {
                this.getSubBillList();
            })
        },
        handleCurrentChange(page) {//改变page回调
            this.formInline.page = page;
            this.getSubBillList();
        },
        handleSizeChange(pageSize) {//改变pageSize
            this.formInline.pageSize = pageSize;
            this.formInline.page = 1;
            this.getSubBillList();
        },
        selectTypeHandle() {//form表单中的选择类型的回调
            this.getSubBillList();
        },
        async returnHandle(id) {
            let res = await viewReceipts({ id });
            this.viewReceiptsImgs = res.data;
            this.viewReceiptsImgs.id = id;
            this.dialogReceipts = true;
        },
        returnHandleClose() {
            this.dialogReceipts = false;
        },
        selectCompanyName(value) {
            this.formInline.company_search = '';
            this.getSubBillList();
        },
        async getAhCompanyList() {
            let res = await getAhCompanyList();
            if (res.code == 200) {
                this.ahCompanyList = res.data;
            }
        },
        selectArea() {
            this.formInline.page = 1;
            this.formInline.pageSize = 10;
            this.getSubBillList();
        },
        handleSelectionChange(val) {
            console.log(val);
            this.multipleSelection = val;
        },
        selectableStatus(row, index) {
            if (row.status == 4) {
                return true
            } else {
                return false
            }
        },

        async deleteSubBill(id) {
            this.$confirm('确定删除该分运单?', '提示', {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                let res = await deleteSubBill({
                    id
                })
                if (res.code == 200) {
                    this.$message.success(res.msg)
                    this.getSubBillList();
                } else {
                    this.$message.error(res.msg)
                }
            }).catch(() => {

            })

        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        if(this.$route.query.yund_id){
            this.formInline.id = this.$route.query.yund_id;
        }
        this.getSubBillList();
        this.getAhCompanyList();
    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类

::v-deep .el-pagination {
    margin-top: 20px;
}

.carTrace {
    ::v-deep .el-dialog {
        height: 80vh;

        .el-dialog__body {
            height: calc(80vh - 55px);
            overflow: hidden;
        }
    }
}

.imgbox3 {
    display: flex;

    .block {
        display: flex;
        padding: 30px;
        width: 30%;
        height: 300px;
        overflow: hidden;
    }

    .demonstration {
        width: 40%;
    }
}

::v-deep .el-table .el-table__cell {
    padding: 10px 0;

    .cell {
        padding-left: 2px;
        padding-right: 2px;
    }
}
</style>